
package com.cszy.yydqbfq.customview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.hbcysd.qybfq.R


class CircleImageView : AppCompatImageView {
    private val clipPath = Path()
    private var radius = 0f

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        attrs?.let { attributeSet ->
            val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CircleImageView)
            radius = typedArray.getDimension(R.styleable.CircleImageView_civ_radius, 0f)
            typedArray.recycle()
        }
    }

    override fun onDraw(canvas: Canvas) {
        canvas?.let {
            clipPath.reset()
            // 修正：使用中心点坐标 (width/2, height/2) 而不是 (width, height)
            clipPath.addCircle(width / 2f, height / 2f, radius, Path.Direction.CW)
            it.clipPath(clipPath)
            super.onDraw(it)
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 如果没有在XML中设置radius，则使用默认值
        if (radius == 0f) {
            radius = minOf(width, height) / 2f
        }
    }

    // 提供外部设置radius的方法
    fun setRadius(customRadius: Float) {
        this.radius = customRadius
        invalidate()
    }
}